<!--
 * @Description: 新增医院对话框
 * @Date: 2023-07-28 10:29:36
 * @FilePath: \hksj-vued:\03code\hk-marketing-crm\src\views\system\hospital\hospitalDialog.vue
-->
<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="43%" :close-on-click-modal="false" @close="dialogRefresh">
			<el-form ref="dialogRef" :rules="state.rules" :model="state.ruleForm" size="default" label-width="150px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="医院所在区域" prop="selectedArea">
							<el-cascader
								ref="cascaderRef"
								:options="state.areaData"
								:props="{ value: 'id', label: 'regionName', expandTrigger: 'hover' }"
								placeholder="请选择医院所在区域"
								clearable
								class="w100"
								v-model="state.ruleForm.selectedArea"
								@change="onHospitalAreaChange"
							>
								<template #default="{ node, data }">
									<span>{{ data.regionName }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="医院名称" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder="请输入医院名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="医院级别" prop="levelId">
							<el-select v-model="state.ruleForm.levelId" value-key="id" placeholder="请选择医院级别" class="w100" @change="onHospitalLevelSelected">
								<el-option v-for="item in state.levelOptions" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="state.dialog.type !== 'projectToAdd'">
						<el-form-item label="医院别名" prop="alias">
							<el-input v-model="state.ruleForm.alias" placeholder="请输入医院别名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="state.dialog.type !== 'projectToAdd'">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" type="textarea" placeholder="请输入备注" maxlength="500"></el-input>
						</el-form-item>
					</el-col> -->
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(dialogRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemHospitalDialog">
import { reactive, ref } from 'vue';
import { useDicApi } from '/@/api/system/dic';
import { useHospitalApi } from '/@/api/system/hospital';
import { ElMessage, FormInstance } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const dialogRef = ref();
const cascaderRef = ref();
const state: any = reactive({
	areaData: [],
	curAreaData: '',
	levelOptions: [], // 医院级别
	curLevelOption: '',

	ruleForm: {
		id: '',
		selectedArea: '',
		name: '', // 名称
		levelId: '',
		levelName: '',
		alias: '', // 别名
		remark: '', // 备注
	},
	rules: {
		name: [{ required: true, message: '请输入医院名称', trigger: 'blur' }],
		levelId: [{ required: true, message: '请输入医院级别', trigger: 'blur' }],
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// 打开弹窗
const openDialog = async (type: string, row: any) => {
	state.dialog.type = type;

	if (type === 'edit') {
		state.ruleForm = {
			id: row.id,
			selectedArea: [row.provinceId, row.cityId, row.districtId].filter(Boolean),
			name: row.name, // 名称
			levelId: row.levelId,
			alias: row.alias, // 别名
			remark: row.remark, // 备注
		};
		state.dialog.title = '修改医院';
		state.dialog.submitTxt = '修 改';
	} else if (type === 'projectToAdd') {
		// 从项目直接新增医院
		state.dialog.title = '新增医院';
		state.dialog.submitTxt = '新 增';
		state.ruleForm = {
			id: '',
			selectedArea: [row.provinceId, row.cityId, row.districtId].filter(Boolean),
			name: '', // 名称
			levelId: '',
			alias: '', // 别名
			remark: '', // 备注
		};
		console.log([row.provinceId, row.cityId, row.districtId]);
	} else {
		state.dialog.title = '新增医院';
		state.dialog.submitTxt = '新 增';
	}
	state.dialog.isShowDialog = true;

	await getAreaData();
	await getLevelData();
};

// 获取区域数据
const getAreaData = async () => {
	const { data } = await useHospitalApi().queryCityTree();
	state.areaData = data;
};

// 获取级别数据
const getLevelData = async () => {
	const { data } = await useDicApi().queryDicInfoAllByTypeId({
		typeId: 'a7bfc26f235c26e1decb6ab80126c8f5',
	});
	state.levelOptions = data.children.sort((a: any, b: any) => a.seq - b.seq);
};

// 医院位置改变
const onHospitalAreaChange = () => {
	state.curAreaData = cascaderRef.value.getCheckedNodes();
};

// 当医院级别选中
const onHospitalLevelSelected = (val: any) => {
	let curLevel = state.levelOptions.find((item: any) => val === item.id);
	state.ruleForm.levelName = curLevel.name;
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};

// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid: any, fields: any) => {
		if (valid) {
			state.curAreaData = cascaderRef.value.getCheckedNodes();
			await addHospital();
			closeDialog();
		} else {
			ElMessage.warning('表格项验证失败,请检查!');
			console.log('表格项验证失败!', fields);
		}
	});
};

const addHospital = async () => {
	let curNode = state.curAreaData[0];

	let params = {
		id: state.dialog.type === 'edit' ? state.ruleForm.id : '',
		provinceId: curNode.pathNodes[0].value,
		provinceName: curNode.pathNodes[0].label,
		cityId: curNode.pathNodes[1]?.value || '',
		cityName: curNode.pathNodes[1]?.label || '',
		districtId: curNode.pathNodes[2]?.value || '',
		districtName: curNode.pathNodes[2]?.label || '',
		directCityId: curNode.value,
		cityIds: curNode.pathValues.join(','),

		name: state.ruleForm.name,
		alias: state.ruleForm.alias,
		levelId: state.ruleForm.levelId,
		levelName: state.ruleForm.levelName,
		remark: state.ruleForm.remark,
	};

	let res = null;
	if (state.dialog.type === 'edit') {
		res = await useHospitalApi().updateHospital(params);
	} else {
		res = await useHospitalApi().addHospital(params);
	}

	if (res.code === 200) {
		ElMessage.success(res.msg || '操作成功');
		emit('refresh', res.data);
	}
};

const dialogRefresh = () => {
	// 清除校验规则+重置数据(只能重置到第一次打开弹框的初始数据,不能清空)
	dialogRef.value?.resetFields();
	// 手动清空数据
	state.ruleForm = {
		id: '',
		selectedArea: '',
		name: '', // 名称
		levelId: '',
		levelName: '',
		alias: '', // 别名
		remark: '', // 备注
	};
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__footer) {
	text-align: center;
}
</style>
